package com.zf.shuashua.ui.popup;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.lxj.xpopup.core.CenterPopupView;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.R;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.manager.DownLoadManager;
import com.zf.shuashua.ui.gift.H5Activity;
import com.zf.shuashua.ui.mine.LogUtil;
import com.zf.shuashua.utils.ToastUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.UUID;

public class GuafenPopup extends CenterPopupView {
    private Activity context;
    private int id;
    private String jump_link;
    private String banner_name;
    private String banner_url;
    private ImageView backdrop;

    public GuafenPopup(@NonNull Activity context, int id, String jump_link, String banner_name, String banner_url) {
        super(context);
        this.id = id;
        this.context = context;
        this.jump_link = jump_link;
        this.banner_name = banner_name;
        this.banner_url = banner_url;
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.popup_guafen;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        boolean isGif = !TextUtils.isEmpty(banner_url) && banner_url.toLowerCase().endsWith(".gif");
        backdrop = findViewById(R.id.img_backdrop);
        if (isGif) {
            Glide.with(context).load(banner_url).diskCacheStrategy(DiskCacheStrategy.DATA).into(backdrop);
        } else {
            Glide.with(context).load(banner_url).into(backdrop);
        }

        findViewById(R.id.img_close).setOnClickListener(view -> dismiss());
        backdrop.setOnClickListener(view -> {
            if (jump_link != null) {
                //活动点击埋点
                HttpData.getInstance().get_record_num("1", id + "", new ACallback<BaseData>() {
                    @Override
                    public void onSuccess(BaseData data) {
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {

                    }
                });
                if(jump_link.contains(".apk")){
                    String packageName = "";
                    if(jump_link.contains("fanyou")){
                        packageName = "com.qinglan.fanyou";
                    }
                    DownLoadManager.getInstance().startDownload(context, jump_link, packageName);
                }else{
                    context.startActivity(new Intent(context, H5Activity.class).putExtra("money", jump_link).putExtra("title", banner_name));
                }
                dismiss();
            }
        });
        if (jump_link == null) {
            backdrop.setOnLongClickListener(view -> {
                //活动点击埋点
                HttpData.getInstance().get_record_num("1", id + "", new ACallback<BaseData>() {
                    @Override
                    public void onSuccess(BaseData data) {

                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                    }
                });
                new SaveImage().execute();
                return false;
            });
        }

    }

    public class SaveImage extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String result = "";
            try {
                String sdcard = Environment.getExternalStorageDirectory().toString();
                File file = new File(sdcard + "/Download");
                if (!file.exists()) {
                    file.mkdirs();
                }
                file = new File(sdcard + "/Download/" + UUID.randomUUID() + ".jpg");
                InputStream inputStream = null;
                java.net.URL url = new java.net.URL(banner_url);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(20000);
                if (conn.getResponseCode() == 200) {
                    inputStream = conn.getInputStream();
                }
                byte[] buffer = new byte[4096];
                int len = 0;
                FileOutputStream outStream = new FileOutputStream(file);
                while ((len = inputStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }
                outStream.close();
                result = "图片保存成功!";
                //发送广播通知手机有图片更新
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(file);
                intent.setData(uri);
                context.sendBroadcast(intent);
            } catch (Exception e) {
                result = "保存失败!";
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            ToastUtils.showShort(result);
            dismiss();
        }
    }


}

